#!/bin/bash

set -e

echo "=== Scheduled Task Platform Starting ==="
echo "Time: $(date)"
echo "Working Directory: $(pwd)"
echo "User: $(whoami)"

# Ensure correct working directory
cd /app

# Check critical files
echo "Checking critical files..."
for file in start_services.py system_management.py models.py; do
    if [ ! -f "/app/$file" ]; then
        echo "Error: Missing file $file"
        exit 1
    fi
done
echo "File check completed"

# Show Python environment
echo "Python: $(python --version)"

# MySQL connection wait
if [ "$DATABASE_TYPE" = "mysql" ]; then
    echo "Waiting for MySQL connection..."
    for i in {1..30}; do
        if mysqladmin ping -h"$MYSQL_HOST" -P"$MYSQL_PORT" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" --silent 2>/dev/null; then
            echo "MySQL connection successful"
            break
        fi
        echo "Waiting for MySQL... ($i/30)"
        sleep 2
    done
    
    # Test connection
    if [ -f "/app/scripts/mysql_manager.py" ]; then
        python /app/scripts/mysql_manager.py test || {
            echo "MySQL connection test failed"
            exit 1
        }
    fi
fi

# Database initialization
echo "Initializing database..."
python /app/system_management.py init_db || {
    echo "Database initialization failed"
    exit 1
}

echo "Initializing permissions..."
python /app/system_management.py init_permissions || {
    echo "Permission initialization failed"
    exit 1
}

# Admin permission fix
python -c "
import sys
sys.path.insert(0, '/app')
try:
    from models import User, db
    from flask import Flask
    import os
    
    app = Flask(__name__)
    
    if os.getenv('DATABASE_TYPE') == 'mysql':
        from config.mysql_config import MySQLConfig
        mysql_config = MySQLConfig()
        mysql_config.validate_config()
        app.config['SQLALCHEMY_DATABASE_URI'] = mysql_config.get_database_uri()
        app.config['SQLALCHEMY_ENGINE_OPTIONS'] = mysql_config.get_engine_options()
    else:
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tasks.db'
    
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    
    with app.app_context():
        admin = User.query.filter_by(username='admin').first()
        if admin and not admin.is_admin:
            admin.is_admin = True
            db.session.commit()
            print('Admin permissions updated')
        else:
            print('Admin permissions normal')
except Exception as e:
    print(f'Permission update error: {e}')
"

echo "=== Starting Services ==="
echo "Environment: DATABASE_TYPE=$DATABASE_TYPE"
echo "MySQL: $MYSQL_HOST:$MYSQL_PORT"

# Start main program
exec python /app/start_services.py